package service;

import FileSave.ParamDto;
import JDBC.DBUtils;
import com.google.gson.JsonObject;
import method.RequestUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @author Gao Shiwei
 * all pictures from user will be uploaded in this interface
 */
@WebServlet(name = "ReceiveImage")
public class ReceiveImage extends HttpServlet {
    public static String filename=null;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Credentials", "true");
       /* DiskFileItemFactory factory =new DiskFileItemFactory();
        ServletFileUpload upload =new ServletFileUpload();
        factory.setSizeThreshold(1024*1024);
        List items=null;
        try{
            items=upload.parseRequest(request);
        }catch (FileUploadException e){
            e.printStackTrace();
        }
        Iterator iter=items.iterator();
        while(iter.hasNext()){
            FileItem item=(FileItem)iter.next();
            if(!item.isFormField()){
                filename=System.currentTimeMillis()+".jpg";
                System.out.println(request.getContextPath());
                File f=new File("D://image");
                if(!f.exists()){
                    f.mkdir();
                }
                String imgsrc=f+"/"+filename;
                InputStream is=item.getInputStream();
                FileOutputStream fos=new FileOutputStream(imgsrc);
                byte b[] =new byte[1024*1024];
                int length=0;
                while(-1!=(length=is.read(b))){
                    fos.write(b,0,length);
                }
                fos.flush();
                fos.close();
            }else{
                System.out.println(item.getFieldName());
                String value=item.getString();
                value=new String(value.getBytes("ISO-8859-1"),"UTF-8");
                System.out.println(value);
            }
        }
        response.sendRedirect("/ServletTest/showPhoto?filename="+filename);*/

        if(ServletFileUpload.isMultipartContent(request)) {
            //System.out.println("zzzz");
            ParamDto dto = RequestUtil.parseParam(request);

            String ItemID = dto.getParamMap().get("ItemID");

            //System.out.println(ItemID);

            FileItem item = dto.getFileMap().get("pic");

            String fileName = item.getName();

            System.out.println(fileName);

            int position=fileName.indexOf(".");

            fileName=fileName.substring(position);

            File myPath=new File(this.getServletContext().getRealPath("/"+ItemID));

            String path = this.getServletContext().getRealPath("/"+ItemID+"/");

            if(!myPath.exists()){
                myPath.mkdir();
            }
            path=path;
            try {
                item.write(new File(path +"/"+ItemID+fileName));
                path=path.replace("\\","\\\\");
                System.out.println(ItemID+"\\\\"+ItemID+fileName);
                DBUtils.addItemPicture(ItemID,ItemID+"\\\\"+ItemID+fileName);
                JsonObject Container=new JsonObject();
                Container.addProperty("answer",ItemID+"\\\\"+ItemID+fileName);
                PrintWriter out = response.getWriter();
                out.println(Container);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
                JsonObject Container=new JsonObject();
                Container.addProperty("answer",false);
                PrintWriter out = response.getWriter();
                out.println(Container);
                out.flush();
                out.close();
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}